import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/endian_help.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/eeg_list.dart';
import 'package:wch/page/login.dart';
import 'package:wch/page/pdf_provider.dart';
import 'package:wch/page/select_hospital.dart';
import 'package:wch/page/setting.dart';
import 'package:wch/page/user_manager.dart';
import 'package:wch/utils/digital_utils.dart';
import 'package:wch/utils/loading_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/config_constant.dart';
import '../constant/mqtt_constant.dart';
import '../constant/text_constant.dart';
import '../helper/mqtt.dart';
import '../main.dart';
import '../model/hospital.dart';
import '../native/native.dart';
import '../utils/tel_sms_service.dart';
import '../utils/text_utils.dart';
import '../widget/common_widget.dart';
import 'dart:convert' as convert;

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>  with RouteAware{
  // double widgetHeight = 0;

  String? doctorName;
  String? hospital;
  String? hospitalId;
  String? department;
  String? sex;
  String? id;

  List<HospitalData> hospitalList = [];
  @override
  void didChangeDependencies() {
    routeObserver.subscribe(
        this, ModalRoute.of(context) as PageRoute);
    super.didChangeDependencies();
  }

  @override
  void didPopNext() {
    super.didPushNext();
    netRequest();
  }

  @override
  void initState() {
    super.initState();

    Connectivity().checkConnectivity();

    statusBarHeight = ScreenUtil().statusBarHeight;
    LogUtils.log('status=$statusBarHeight');
    Timer(Duration(milliseconds: 500), () {
      if (!PreferencesHelper.tokenIsValid()) {
        NavigatorUtil.replace(context, LoginPage());
      } else {
        ///请求权限-Android
        NativeUtils.requestPermission();

        netRequest();

        ///连接 mqtt
        connectMqtt();
      }
    });

  }
  
  String showDoctorName(String? name) {
    if (name == null) return '';
    if (name.length > 4) {
      return '${name.substring(0, 3)}...';
    }
    return name;
  }

  void netRequest() {
    NetBusiness().doctorInfo().then((value) {
      setState(() {
        doctorName = value.name;
        hospital = value.hospital;
        department = value.department;
        hospitalId = value.hospitalId;
        sex = value.sex;
        id = value.id.toString();
      });
      PreferencesHelper.setDepartment(department ?? '');
      PreferencesHelper.setPerson(doctorName ?? '');
    });

    NetBusiness().hospitalList().then((value) {
      setState(() {
        setState(() {
          hospitalList = value.data!;
        });
      });
    });
  }

  GlobalKey key1 = GlobalKey();
  GlobalKey key2 = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: Container(
        child: Container(
          decoration: BoxDecoration(color: themeBGC),
          child: ConstraintLayout(
            children: [
              Image.asset(
                homeBackgroundPng,
                width: ScreenUtil().screenWidth,
                height: ScreenUtil().screenWidth/2,
                fit: BoxFit.fitWidth,
              ).applyConstraint(
                  left: parent.left,
                  right: parent.right,
                  top: parent.top.margin(-10.h),
                  height: 200,
                  zIndex: 0),
              Column(
                children: [
                  ShadowContainer(
                    horPadding: 0,
                    verPadding: 0,
                    height: 125.h,
                    width: ScreenUtil().screenWidth-50.w,
                    child: ConstraintLayout(
                      children: [
                        Image.asset(
                          hospitalHeadPng,
                          width: 70.w,
                          height: 70.w,
                        ).applyConstraint(
                            left: parent.left.margin(10.w),
                            centerVerticalTo: parent,
                            size: 100.h),
                        Text(showDoctorName(doctorName), style: TextStyle(
                          color: Color(0xFF3E3F42),
                          fontSize: 20,
                          fontWeight: FontWeight.w500
                        ),).applyConstraint(
                            left: rId(0).right.margin(10.w),
                            top: rId(0).top.margin(15.w)
                        ),
                        Image.asset(sex == 'M' ? hospitalMaleIcon :hospitalFemaleIcon, width: 20, height: 20,).applyConstraint(
                            left: rId(1).right.margin(5.w),
                            centerVerticalTo: rId(1)
                        ),
                        GestureDetector(
                          onTap: (){
                            NavigatorUtil.push(context, SelectHospitalPage(hospital: hospital ?? '', hospitalId: hospitalId ?? '0', hospitalList: hospitalList,));
                          },
                          child: Offstage(
                            offstage: hospitalList.length <= 1,
                            child: Container(
                              decoration: BoxDecoration(
                                color: themeColor,
                                borderRadius: BorderRadius.all(Radius.circular(15.h)),
                              ),
                              // padding: EdgeInsets.all(5.w),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: [
                                  Image.asset(homeChangeBtnPng, width: 10, height: 10,),
                                  F11TitleText('切换医院', color: Colors.white),
                                ],
                              )
                            ),
                          )
                        ).applyConstraint(
                            right: parent.right.margin(15.w),
                            width: 75.w,
                            height: 31.h,
                            centerVerticalTo: rId(2)
                        ),
                        F12TitleText(department ?? '', color: Color(0xFF676767)).applyConstraint(
                          left: rId(1).left,
                          right: parent.right.margin(15.w),
                          width: matchConstraint,
                          top: rId(1).bottom.margin(3.5.h),
                        ),
                        F12TitleText(hospital ?? '', color: Color(0xFF676767)).applyConstraint(
                          left: rId(1).left,
                          right: parent.right.margin(15.w),
                          width: matchConstraint,
                          top: rId(4).bottom.margin(3.5.h),
                        ),
                        // Container(
                        //   child: SizedBox(
                        //     width: ScreenUtil().screenWidth-180.w,
                        //     height: widgetHeight,
                        //     child: Stack(
                        //       children: widgets,
                        //     ),
                        //   )
                        // ).applyConstraint(
                        //     right: parent.right.margin(10.w),
                        //     bottom: parent.bottom.margin(10.h),
                        //     width: ScreenUtil().screenWidth-180.w,
                        //     height: widgetHeight
                        // ),
                      ],
                    ),
                  ),
                  VerPadding(20.h),
                  _getItem(0),
                  VerPadding(20.h),
                  _getItem(1),
                  VerPadding(20.h),
                  _getItem(2),
                ],
              ).applyConstraint(
                  left: parent.left,
                  right: parent.right,
                  top: rId(0).bottom.margin(-70.h)),
              Text('脑电睡眠监测系统', style: TextStyle(
                  fontFamily: 'PangMenZhengDao',
                  fontSize: 25,
                  color: Colors.white
              ),).applyConstraint(
                  left: parent.left.margin(45.w),
                  top: parent.top.margin(65.h)
              )
            ],
          ),
        ),
      ),
    );
  }

  // List<Widget> _getDoctorWidget() {
  //   // return Container(
  //   //   margin: EdgeInsets.symmetric(horizontal: 20.w),
  //   //   padding: EdgeInsets.all(10.w),
  //   //   child: ,
  //   // )
  //   double width = ScreenUtil().screenWidth - 180.w;
  //   List<String> flags = [
  //     '骨科',
  //     '骨科',
  //     '骨科',
  //     '骨科1111111',
  //     '骨科',
  //     '骨科',
  //     '骨科',
  //   ];
  //
  //   List<Widget> widgets = [Container()];
  //
  //   widgetHeight = 0;
  //   double posX = 0;
  //   for (int i = 0; i < flags.length; i++) {
  //     Size size = _getTextSize(flags[i]);
  //     if (widgetHeight == 0) {
  //       widgetHeight = size.height; //10 代表上下边距
  //     }
  //     posX += size.width + 10;
  //     if (posX > width) {
  //       posX = size.width + 10;
  //       widgetHeight += size.height; //加上外边距和下一行的高度
  //     }
  //
  //     widgets.add(
  //       Positioned(
  //         left: posX - size.width - 10,
  //         top: widgetHeight - size.height,
  //         width: size.width+10,
  //         height: size.height,
  //         child: F13TitleText(
  //         flags[i],
  //         color: F1TextColor,
  //       ),)
  //     );
  //
  //     posX += 5;
  //   }
  //   return widgets;
  // }

  Size _getTextSize(String text) {
    TextStyle style = const TextStyle(
      fontSize: 13,
    );
    return TextUtils.boundingTextSize(text, style,
        maxWidth: ScreenUtil().screenWidth - 180.w);
  }

  Widget _getItem(int index) {
    return GestureDetector(
      onTap: (){
        if (index == 0) {
          NavigatorUtil.push(context, const UserManagerPage());
        } else if (index == 1) {
          NavigatorUtil.push(context, const EEGListPage());
        } else if (index == 2) {
          NavigatorUtil.push(context, SettingPage(id: id!,));
        }
      },
      child: Container(
        height: 127.h,
        margin: EdgeInsets.symmetric(horizontal: 25.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10.h)),
          image: DecorationImage(image: AssetImage(homeMenuImage[index]),
            fit: BoxFit.fill,)
        ),
        child: Row(
          children: [
            // Expanded(child: Container()),
            //
            // Image.asset(arrowRightPng, width: 12.w, height: 13.w,),
            // HorPadding(48.w)
            HorPadding(159.w),
            MyText(homeMenu[index], color: const Color(0xFF3E3F42), fontSize: 22),
            HorPadding(20.w),
            Image.asset(arrowRightPng, width: 12.w, height: 13.w,),
          ],
        ),
        // child: Row(
        //   mainAxisAlignment: MainAxisAlignment.start,
        //   children: [
        //     HorPadding(40.w),
        //     Image.asset(
        //       'images/common/icon_weixin.png',
        //       width: 80,
        //       height: 80,
        //     ),
        //     HorPadding(40.w),
        //     Row(
        //       mainAxisAlignment: MainAxisAlignment.start,
        //       children: [
        //         F18TitleText(homeMenu[index], color: F1TextColor),
        //         HorPadding(20.w),
        //         Image.asset(
        //           'images/common/icon_weixin.png',
        //           width: 30,
        //           height: 30,
        //         ),
        //       ],
        //     )
        //   ],
        // ),
      ),
    );
  }
}
